/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.data.ui.swing;

import cn.ekuma.data.dao.I_DataLogic;
import cn.ekuma.data.dao.I_ParentNode;
import cn.ekuma.data.dao.ParentNode;
import cn.ekuma.data.dao.bean.I_BaseBean;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public abstract class JChildKeyViewDAOEditorPanel<K,V>  extends AbstractJXTablePanel implements ParentNodeChangeListener<K>{
    AbstractChildDAOJEditor editor;
    JEditorWarpDialog editorDialog;
    I_DataLogic dlSales;
    AbstractDTOTableModel tableModel;

    public JChildKeyViewDAOEditorPanel(I_DataLogic dlSales,AbstractDTOTableModel<V> tableModel,AbstractChildDAOJEditor editor) {
        super();
        this.editor = editor;
        this.dlSales=dlSales;
        this.tableModel=tableModel;
        editorDialog= JEditorWarpDialog.getInstance(this).init(dlSales, editor);
        getJXTable().setModel(tableModel);
    }

    @Override
    public boolean removeSelectedObjects(int[] rows) {
      List objs=new ArrayList();
      for(int i:rows){
          objs.add(coverViewToBean((V) tableModel.getObj(getJXTable().convertColumnIndexToModel(i))));
      }
      try {
          for(Object obj:objs){
            dlSales.delete((I_BaseBean)obj);
            tableModel.remove(obj);
          }
       } catch (BasicException ex) {
            new MessageInf(ex).show(this);
            return false;
       }
      return true;
    }

    @Override
    public void addObject() {
        editorDialog.writeValueInsert(null);
        if(editorDialog.getRetObj()!=null)
             tableModel.add(coverBeanToView((K) editorDialog.getRetObj()));
    }

    public String getTabName(){
        return editor.getTabName();
    }

    public void parentNodeValueChange(int state, I_ParentNode<K> parent) {
    	parent=new ParentNode<K>(parent);
        editor.setParentNode(parent);
        editor.setParentState(state);
        if (state == AbstractChildDAOJEditor.STATE_Edit) {
            updateUI(true);
            try {
            tableModel.resert(dlSales.listByParent(getViewBeanClass(), parent));
        } catch (BasicException ex) {
            Logger.getLogger(JChildDAOEditorPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        } else {
            updateUI(false);
            tableModel.resert(null);
        }
    }

    public abstract K coverViewToBean(V obj);

    public abstract V coverBeanToView(K obj);

    public abstract Class getViewBeanClass();
}
